package com.erlang.springmvc.controller;

import com.erlang.springmvc.pojo.Customer;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Description：pojo对象参数绑定
 */
@Controller
@RequestMapping(value = "pojo-type")
public class PojoTypeController {

    /**
     * 问题: Customer.java 的createTime 属性是 Date 类型的，而我们输入的是字符串类型，故绑定不了
     * 方案一:
     *  1. 使用@initBinder注解配合 WebDataBinder实现将请求request绑定到复杂属性时的请求字符string到属性的转换
     *
     * @Description 实现时间格式的处理
     */
    @InitBinder
    public void initBinder(WebDataBinder binder){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //new CustomDateEditor(simpleDateFormat, true)的true表示是否可以传递空值
        binder.registerCustomEditor(Date.class, new CustomDateEditor(simpleDateFormat, true));
    }

    /**
     * @Description 去操作页面
     */
    @RequestMapping(value = "to-pojo-type")
    public ModelAndView toPojoType(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pojo-type");
        return modelAndView;
    }

    /**
     * @Description 传递页面
     */
    @RequestMapping(value = "do-pojo-type")
    public ModelAndView pojoType(@RequestBody Customer customer){
        ModelAndView modelAndView = new ModelAndView();
        System.out.println("接受到的customer信息："+customer.toString());
        modelAndView.addObject("customer", customer.toString());
        modelAndView.setViewName("pojo-type");
        return modelAndView;
    }
}